<template>
    <div>
        <Form
            ref="entityForm"
            class="page-sys-user-drawer-form"
            :model="entity"
            :rules="entityRules"
            :disabled="drawerType === 'read'"
            label-position="top"
            label-colon
            hide-required-mark
        >
            <Row :gutter="32"> </Row>
            <Divider />
        </Form>
        <div class="page-sys-user-drawer-footer" v-if="drawerType != 'read'">
            <Button
                type="primary"
                @click="handleSubmitEdit"
                :loading="submitting"
                >提交</Button
            >
        </div>
    </div>
</template>
<script>
    import { mapState } from "vuex";
    import { SaveData, GetData } from "@api/consumelog";

    export default {
        name: "table-form",
        props: {
            entityId: String,
            drawerType: String
        },
        data() {
            return {
                submitting: false,
                entity: {
                    id: null
                },
                entityRules: {}
            };
        },
        computed: {
            ...mapState("admin/layout", ["isMobile"]),
            labelWidth() {
                return this.isMobile ? undefined : 100;
            },
            labelPosition() {
                return this.isMobile ? "top" : "right";
            }
        },
        methods: {
            initEntity() {
                GetData(this.entityId).then(res => {
                    if (res.errcode != 0) {
                        this.$Message.error(res.msg);
                        return;
                    }
                    this.entity = res.data;
                });
            },
            handleSubmitEdit() {
                this.$refs.entityForm.validate(valid => {
                    if (valid) {
                        if (this.submitting) return;
                        this.submitting = true;

                        SaveData(this.entity).then(res => {
                            this.submitting = false;
                            if (res.errcode != 0) {
                                this.$Message.error(res.msg);
                                return;
                            }
                            this.$emit("saveFinished");
                        });
                    }
                });
            }
        },
        mounted() {
            if (this.entityId) this.initEntity();
        }
    };
</script>
